<template>
  <div class="notification-center">
    <!-- 通知图标按钮 -->
    <div class="notification-icon" @click="toggleNotifications">
      <i class="el-icon-bell"></i>
      <div v-if="unreadCount > 0" class="notification-badge">{{ unreadCount > 99 ? '99+' : unreadCount }}</div>
    </div>
    
    <!-- 通知弹窗 -->
    <div v-if="isOpen" class="notification-popup">
      <div class="notification-header">
        <h3>消息通知</h3>
        <div class="notification-actions">
          <span @click="markAllAsRead" class="mark-all-read">全部标为已读</span>
          <span @click="toggleNotifications" class="close-btn"><i class="el-icon-close"></i></span>
        </div>
      </div>
      
      <div class="notification-list" v-if="notifications.length > 0">
        <div 
          v-for="notification in notifications" 
          :key="notification.id" 
          class="notification-item"
          :class="{'unread': !notification.is_read}"
          @click="handleNotificationClick(notification)"
        >
          <div class="notification-avatar">
            <el-avatar 
              :size="40" 
              :src="notification.sender_avatar" 
              @error="handleAvatarError">
            </el-avatar>
          </div>
          <div class="notification-content">
            <div class="notification-sender">{{ notification.notification_type === 'SYSTEM' ? '系统通知' : (notification.sender_name || '未知用户') }}</div>
            <div class="notification-message">{{ getNotificationContent(notification) }}</div>
            <div class="notification-time">{{ formatTime(notification.created_at) }}</div>
          </div>
          <div class="notification-badge-dot" v-if="!notification.is_read"></div>
        </div>
      </div>
      
      <div v-else class="empty-notification">
        <i class="el-icon-bell empty-icon"></i>
        <p>暂无通知</p>
      </div>
      
      <div class="view-all">
        <router-link to="/notifications">查看全部通知</router-link>
      </div>
    </div>
    
    <!-- 背景遮罩 -->
    <div v-if="isOpen" class="notification-backdrop" @click="toggleNotifications"></div>
  </div>
</template>

<script>
import { getNotifications, getUnreadNotificationsCount, markNotificationAsRead, markAllNotificationsAsRead, getActivityIdByCommentId } from '@/api/api';
import defaultAvatar from "@/assets/images/default-avatar.jpg"; // 导入默认头像

export default {
  name: 'NotificationCenter',
  data() {
    return {
      isOpen: false,
      notifications: [],
      unreadCount: 0,
      loading: false,
      currentPage: 1,
      pageSize: 5, // 弹窗中只显示前5条
      defaultAvatar: defaultAvatar // 添加默认头像
    };
  },
  methods: {
    toggleNotifications() {
      this.isOpen = !this.isOpen;
      if (this.isOpen) {
        this.fetchNotifications();
      }
    },
    
    async fetchNotifications() {
      this.loading = true;
      try {
        // 获取通知列表
        const response = await getNotifications(this.currentPage, this.pageSize);
        this.notifications = response.records || [];
        
        // 获取未读通知数量
        const countResponse = await getUnreadNotificationsCount();
        this.unreadCount = countResponse.count || 0;
      } catch (error) {
        console.error('获取通知失败:', error);
      } finally {
        this.loading = false;
      }
    },
    
    async fetchUnreadCount() {
      try {
        const response = await getUnreadNotificationsCount();
        console.log('获取未读通知数量响应:', response);
        // 检查不同的返回格式
        if (response.hasOwnProperty('count')) {
          this.unreadCount = response.count || 0;
        } else if (typeof response === 'number') {
          this.unreadCount = response;
        } else {
          this.unreadCount = 0;
        }
      } catch (error) {
        console.error('获取未读通知数量失败:', error);
        this.unreadCount = 0;
      }
    },
    
    async markAllAsRead() {
      try {
        await markAllNotificationsAsRead();
        // 更新已读状态
        this.notifications.forEach(notification => {
          notification.is_read = true;
        });
        this.unreadCount = 0;
        this.$message.success('已全部标记为已读');
      } catch (error) {
        console.error('标记已读失败:', error);
        this.$message.error('操作失败，请稍后重试');
      }
    },
    
    async handleNotificationClick(notification) {
      if (!notification.is_read) {
        try {
          await markNotificationAsRead(notification.id);
          notification.is_read = true;
          this.unreadCount = Math.max(0, this.unreadCount - 1);
        } catch (error) {
          console.error('标记通知已读失败:', error);
        }
      }
      
      // 导航到目标内容
      this.navigateToTarget(notification);
    },
    
    navigateToTarget(notification) {
      // 关闭通知面板
      this.isOpen = false;
      
      // 基于resource_type和notification_type决定如何跳转
      const resourceType = notification.resource_type;
      const resourceId = notification.resource_id;
      const notificationType = notification.notification_type;
      
      // 如果是活动类型的资源
      if (resourceType === 'ACTIVITY') {
        // 存储activityId到localStorage，参考CommonCard
        localStorage.setItem("activityId", resourceId);
        // 跳转到活动详情页
        this.$router.push({ 
          name: 'activity_detail', 
          query: { id: resourceId }
        });
      } 
      // 如果是评论类型的资源
      else if (resourceType === 'COMMENT') {
        // 首先尝试直接从notification对象中获取activity_id
        let activityId = notification.activity_id;
        
        // 如果没有直接的activity_id，从metadata中查找
        if (!activityId && notification.metadata) {
          try {
            const metadataObj = JSON.parse(notification.metadata);
            if (metadataObj.activity_id) {
              activityId = metadataObj.activity_id;
            }
          } catch (error) {
            console.error('解析metadata失败:', error);
          }
        }
        
        // 如果还是没有找到activity_id，调用新的API接口获取
        if (!activityId) {
          this.$message.info('正在获取活动信息...');
          // 显示加载中状态
          const loading = this.$loading({
            lock: true,
            text: '加载中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          
          getActivityIdByCommentId(resourceId)
            .then(response => {
              loading.close();
              if (response && response.activity_id) {
                // 存储activityId到localStorage
                localStorage.setItem("activityId", response.activity_id);
                
                // 跳转到活动详情页，并携带评论ID
                this.$router.push({ 
                  name: 'activity_detail', 
                  params: { id: response.activity_id },
                  query: { commentId: resourceId }
                });
              } else {
                this.$message.warning('无法找到对应的活动信息');
              }
            })
            .catch(error => {
              loading.close();
              console.error('获取评论活动ID失败:', error);
              this.$message.error('获取活动信息失败，请稍后重试');
            });
        } else {
          // 如果已经有activity_id，直接跳转
          localStorage.setItem("activityId", activityId);
          
          this.$router.push({ 
            name: 'activity_detail', 
            query: { id: activityId, commentId: resourceId }
          });
        }
      }
      // 系统通知
      else if (notificationType === 'SYSTEM' || resourceType === 'SYSTEM') {
        // 系统通知通常不需要跳转
        this.$message.info('这是一条系统通知');
      }
      // 处理未知资源类型
      else {
        console.warn('未知的资源类型:', resourceType, '通知类型:', notificationType);
        // 尝试根据通知类型进行兜底处理
        const typeActionMap = {
          'COMMENT': '评论',
          'REPLY': '回复',
          'LIKE_ACTIVITY': '点赞活动',
          'LIKE_COMMENT': '点赞评论',
          'MENTION': '提及'
        };
        const actionText = typeActionMap[notificationType] || '通知';
        this.$message.info(`收到${actionText}通知，但无法确定跳转目标`);
      }
    },
    
    formatTime(timestamp) {
      if (!timestamp) return '';
      
      const now = new Date();
      const date = new Date(timestamp);
      const diff = now - date;
      
      // 计算时间差
      const minutes = Math.floor(diff / 1000 / 60);
      const hours = Math.floor(minutes / 60);
      const days = Math.floor(hours / 24);
      
      // 如果小于1分钟
      if (minutes < 1) {
        return '刚刚';
      }
      // 如果小于1小时
      if (minutes < 60) {
        return `${minutes}分钟前`;
      }
      // 如果小于24小时
      if (hours < 24) {
        return `${hours}小时前`;
      }
      // 如果小于7天
      if (days < 7) {
        return `${days}天前`;
      }
      
      // 如果是今年
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      
      if (year === now.getFullYear()) {
        return `${month}月${day}日`;
      }
      
      // 如果是往年
      return `${year}年${month}月${day}日`;
    },
    
    // 添加头像加载错误处理方法
    handleAvatarError(e) {
      e.target.src = this.defaultAvatar;
    },
    
    // 添加解析通知内容的方法
    getNotificationContent(notification) {
      // 首先尝试从content字段获取内容
      if (notification.content) {
        return notification.content;
      }
      
      // 如果有message字段，使用message字段
      if (notification.message) {
        return notification.message;
      }
      
      // 尝试解析metadata字段
      if (notification.metadata) {
        try {
          const metadataObj = JSON.parse(notification.metadata);
          if (metadataObj.content) {
            // 去除可能的多余换行符
            return metadataObj.content.trim();
          }
          if (metadataObj.message) {
            return metadataObj.message.trim();
          }
        } catch (error) {
          console.error('解析metadata失败:', error);
        }
      }
      
      // 如果以上都失败，根据通知类型返回默认文本
      const typeTextMap = {
        'COMMENT': '收到了新评论',
        'REPLY': '收到了回复',
        'LIKE_ACTIVITY': '点赞了你的活动',
        'LIKE_COMMENT': '点赞了你的评论',
        'MENTION': '在帖子中提到了你',
        'SYSTEM': '系统通知'
      };
      
      return typeTextMap[notification.notification_type] || '收到一条新通知';
    }
  },
  mounted() {
    // 初始化时获取一次未读数量
    this.fetchUnreadCount();
    
    // 模拟轮询，每隔一段时间获取一次未读通知数量
    this.pollingInterval = setInterval(() => {
      this.fetchUnreadCount();
    }, 30000); // 30秒轮询一次
  },
  beforeDestroy() {
    // 清除轮询定时器
    if (this.pollingInterval) {
      clearInterval(this.pollingInterval);
    }
  }
};
</script>

<style scoped>
.notification-center {
  position: relative;
  display: inline-block;
}

.notification-icon {
  cursor: pointer;
  position: relative;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.notification-icon i {
  font-size: 20px;
  color: #fff;
}

.notification-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background-color: #f56c6c;
  color: white;
  border-radius: 10px;
  min-width: 16px;
  height: 16px;
  font-size: 10px;
  line-height: 16px;
  text-align: center;
  padding: 0 4px;
}

.notification-popup {
  position: absolute;
  top: 40px;
  right: -10px;
  width: 350px;
  max-height: 500px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 2001;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

.notification-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.notification-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.mark-all-read {
  font-size: 13px;
  color: #606266;
  cursor: pointer;
}

.mark-all-read:hover {
  color: #409EFF;
}

.close-btn {
  cursor: pointer;
  color: #909399;
}

.close-btn:hover {
  color: #606266;
}

.notification-list {
  overflow-y: auto;
  max-height: 400px;
}

.notification-item {
  display: flex;
  padding: 12px 15px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  position: relative;
  transition: background-color 0.3s;
  align-items: center;
}

.notification-item:hover {
  background-color: #f5f7fa;
}

.notification-item.unread {
  background-color: #f0f9ff;
}

.notification-avatar {
  margin-right: 12px;
}

.notification-content {
  flex: 1;
}

.notification-sender {
  font-size: 13px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 2px;
}

.notification-message {
  font-size: 14px;
  color: #303133;
  line-height: 1.4;
  word-break: break-all;
}

.notification-time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.notification-badge-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #f56c6c;
  position: absolute;
  right: 15px;
  top: 12px;
}

.empty-notification {
  padding: 30px 0;
  text-align: center;
  color: #909399;
}

.empty-icon {
  font-size: 40px;
  color: #c0c4cc;
  margin-bottom: 10px;
}

.view-all {
  padding: 10px 15px;
  text-align: center;
  border-top: 1px solid #ebeef5;
}

.view-all a {
  color: #409EFF;
  text-decoration: none;
  font-size: 14px;
}

.notification-backdrop {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 2000;
}

@media screen and (max-width: 768px) {
  .notification-popup {
    width: 300px;
    right: -80px;
  }
  
  .notification-popup::after {
    right: 88px;
  }
}
</style>